package vip.xiaonuo.vein.model;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.xiaonuo.vein.modular.veindeviceevent.entity.VeinDeviceEvent;
import vip.xiaonuo.vein.modular.veindeviceevent.enums.VeinDeviceEventStatusEnum;
import vip.xiaonuo.vein.modular.veindeviceevent.service.VeinDeviceEventService;
import vip.xiaonuo.vein.service.sn.RedisSnGenerate;

import java.util.List;
import java.util.UUID;


@Component
public class ReqUtil {


    @Autowired
    private VeinDeviceEventService veinDeviceEventService;

    @Autowired
    private RedisSnGenerate redisSnGenerate;

    public String getReqSeriNo(Object data) {
        String serialNumber = UUID.randomUUID().toString().replace("-", "").substring(0, 4);
        String json_str = JSON.toJSONString(data);
        String md5 = DigestUtils.md5Hex(json_str);
        String reqSeriNo = md5.substring(0, 4) + serialNumber;
        List<VeinDeviceEvent> veinDeviceEvents = veinDeviceEventService.list(new LambdaQueryWrapper<VeinDeviceEvent>()
                .eq(VeinDeviceEvent::getSerialNumber, reqSeriNo).eq(VeinDeviceEvent::getStatus, VeinDeviceEventStatusEnum.UN_EXECUTED.getCode()));
        if (CollectionUtil.isNotEmpty(veinDeviceEvents)) {
            reqSeriNo=getReqSeriNo(data);
        }
        return reqSeriNo;
    }

    public String getReqSeriNo(String key,Object data) {
        String serialNumber = redisSnGenerate.getSnNo(key);
        String md5 = DigestUtils.md5Hex(JSON.toJSONString(data));
        String reqSeriNo = md5.substring(0, 4) + serialNumber;
        List<VeinDeviceEvent> veinDeviceEvents = veinDeviceEventService.list(new LambdaQueryWrapper<VeinDeviceEvent>()
                .eq(VeinDeviceEvent::getSerialNumber, reqSeriNo).eq(VeinDeviceEvent::getStatus, VeinDeviceEventStatusEnum.UN_EXECUTED.getCode()));
        if (CollectionUtil.isNotEmpty(veinDeviceEvents)) {
            reqSeriNo = getReqSeriNo(key,data);
        }
        return reqSeriNo;
    }
}
